﻿using System.IO;

using Utilities.IO;
using Utilities.Media.Containers.Riff;

namespace Utilities.Media.Containers.Wav
{
    public enum AudioFormat : short
    {
        PCM = 1
    }

    public class FmtChunk : RiffChunk
    {
        public AudioFormat AudioFormat { get; protected set; }
        public short NumChannels { get; protected set; }
        public int SampleRate { get; protected set; }
        public int ByteRate { get; protected set; }
        public short BlockAlign { get; protected set; }
        public short BitsPerSample { get; protected set; }

        public FmtChunk(DataStream stream)
        {
            ID = stream.ReadString(4);
            Size = stream.ReadInt32();

            if (ID != "fmt ")
                throw new InvalidDataException();
            if (Size != 16)
                throw new InvalidDataException();

            AudioFormat = (AudioFormat)stream.ReadInt16();
            NumChannels = stream.ReadInt16();
            SampleRate = stream.ReadInt32();
            ByteRate = stream.ReadInt32();
            BlockAlign = stream.ReadInt16();
            BitsPerSample = stream.ReadInt16();

            if (ByteRate != SampleRate * NumChannels * BitsPerSample / 8)
                throw new InvalidDataException();
            if (BlockAlign != NumChannels * BitsPerSample / 8)
                throw new InvalidDataException();
        }
        public FmtChunk(short numChannels, short bitsPerSample, int sampleRate, AudioFormat audioFormat)
        {
            ID = "fmt ";
            Size = 16;

            AudioFormat = audioFormat;
            NumChannels = numChannels;
            BitsPerSample = bitsPerSample;
            SampleRate = sampleRate;
            ByteRate = SampleRate * NumChannels * BitsPerSample / 8;
            BlockAlign = (short)(NumChannels * BitsPerSample / 8);
        }
    }
}
